//@ts-nocheck
import indexdb from './indexdb'
/**
 * dbName: "_fas",   //数据库名称
        objName: "portal_cache",  // 表名称
        param: { a: 1 },   // id值
        response: {        // 存储的value
          b: 2,
        },
 */
class LocalCache {
  CACHE_KEY = '_fas_portal_cache'
  constructor(maxCount) {
    this.maxCount = maxCount
    this.cache = JSON.parse(localStorage.getItem(this.CACHE_KEY)) || {}
    this.indexDb = new indexdb()
    if(this.cache&&Object.keys(this.cache.length>0)&&this.indexDb.canUse()){
      for(let i in this.cache){
        this.indexDb.update({
          dbName: '_fas', //数据库名称
          objName: 'portal_cache', // 表名称
          param: i, // id值
          response: this.cache[i]
        })
      }
      
    }
    delete localStorage[this.CACHE_KEY]
  }

  set(key, value) {
    

    //   this.cache[key] = {
    //     //version: this.version,
    //     data: value
    //   };
    if (this.indexDb.canUse()){
      const item = { data: value }
      this.cache[key] = item
      this.indexDb.update({
        dbName: '_fas', //数据库名称
        objName: 'portal_cache', // 表名称
        param: key, // id值
        response: item
      })
      if (Object.keys(this.cache).length > this.maxCount) {
        const oldestKey = Object.keys(this.cache).shift()
        delete this.cache[oldestKey]
        this.indexDb.remove({
          dbName: '_fas',
          objName: 'portal_cache',
          param: key
        })
      }
    }
    return
    try {
      localStorage.setItem(this.CACHE_KEY, JSON.stringify(this.cache))
    } catch (e) {
      if (e.name === 'QuotaExceededError') {
        console.warn('localStorage空间不足，未能有限存储数据')
      }
    }
  }

  get(key) {
    
    const cachedData = this.cache[key]
    if (cachedData) {
      return cachedData.data
    }else if (this.indexDb.canUse()) {
      return this.indexDb.read({
        dbName: '_fas',
        objName: 'portal_cache',
        param: key
      })
    }
    return null
  }

  remove(key) {
    if (this.indexdb.canUse()) {
      this.indexDb.remove({
        dbName: '_fas',
        objName: 'portal_cache',
        param: key
      })
      return
    }
    // return

    // delete this.cache[key]
    // localStorage.setItem(this.CACHE_KEY, JSON.stringify(this.cache))
  }

  clear() {
    this.cache = {}
    localStorage.removeItem(this.CACHE_KEY)
  }
}

class PortalCache {
  constructor() {
    this.cache = new LocalCache(20)
  }
  _genetateHashKey(keyString: string) {
    let hash = CryptoJS.MD5(keyString)
    let hashString: string = hash.toString()
    return hashString
  }
  getRenderData(keyString: string) {
    let hashString = this._genetateHashKey(keyString)
    return this.cache.get(hashString)
  }
  setRenderData(keyString: string, _data: any) {
    let hashString = this._genetateHashKey(keyString)
    this.cache.set(hashString, _data)
  }
}

const portalCache = new PortalCache()

export default portalCache
